<template>
    <div class="repair">
        <MyHeader></MyHeader>
        <van-form
            show-error
            scroll-to-error
            label-width="25vw"
            @submit="onSubmit"
            @failed="onFailed" 
        >
            <my-title>逝者信息</my-title>
            <van-field 
                v-model="formData.gaz_ex3" 
                :readonly="isReadonly"
                required
                center
                name="gaz_ex3" 
                label="逝者姓名"
                placeholder="逝者姓名" 
                :rules="[{ required: true, message: '请填写逝者姓名' }]"
            >
                <template 
                    v-if="!isReadonly" 
                    #button
                >
                    <van-uploader 
                        v-model="dataArr.sh_ex36" 
                        :readonly="isReadonly"
                        :preview-image="false" 
                        :before-delete="beforeDelete('sh_ex36')" 
                        :before-read="beforeRead" 
                        :after-read="afterRead('sh_ex36', true)"
                    >
                        <van-button 
                            size="small" 
                            icon="plus" 
                            type="primary" 
                            native-type="button"
                        >
                            拍照识别
                        </van-button>
                    </van-uploader>
                </template>
            </van-field>

            <van-field 
                v-model="formData.sh_ex2" 
                :readonly="isReadonly"
                required
                center
                name="sh_ex2" 
                label="逝者身份证"
                placeholder="逝者身份证" 
                :rules="[{ required: true, message: '请填写逝者身份证' },{ validator: validator, message: '请填写正确的逝者身份证' }]"
            />
            <van-field 
                v-model="formData.sh_ex3" 
                required
                readonly
                center
                name="sh_ex3" 
                label="逝者性别"
                placeholder="逝者性别" 
            />
            <van-field 
                v-model="formData.sh_ex4" 
                type="digit"
                required
                readonly
                center
                name="sh_ex4" 
                label="逝者年龄"
                placeholder="逝者年龄" 
            />
            <van-field 
                required
                readonly
                center
                name="sh_ex36" 
                label="逝者身份证"
                :rules="[{ validator: validator2('sh_ex36'), message: '请上传逝者身份证' }]"
            />
            <div class="uploader-box">
                <van-uploader 
                    v-model="dataArr.sh_ex36" 
                    :readonly="isReadonly"
                    :max-count="1" 
                    upload-text="逝者身份证" 
                    :before-delete="beforeDelete('sh_ex36')" 
                    :before-read="beforeRead" 
                    :after-read="afterRead('sh_ex36')"
                    :deletable="!isReadonly"
                >
                    <template #default>
                        <img src="@/assets/uploader/uploader.png" />
                    </template>
                </van-uploader>
            </div>
            <my-title>预约安葬信息</my-title>
            <FieldPopupDatePicker v-model:field="formData.gaz_ex4" name="gaz_ex4" label="落葬日期" :readonly="isReadonly" />
            <FieldPopupDatePicker v-model:field="formData.gaz_dat1" name="gaz_dat1" label="到达日期" :readonly="isReadonly" />

            <van-field 
                v-model="formData.gaz_ex1" 
                :readonly="isReadonly"
                required
                center
                name="gaz_ex1" 
                label="墓穴位置"
                placeholder="墓穴位置" 
                :rules="[{ required: true, message: '请填写墓穴位置' }]"
            />
            <my-title>预约人信息</my-title>
            <van-field 
                v-model="formData.gaz_ex2" 
                :readonly="isReadonly"
                required
                center
                name="gaz_ex2" 
                label="预约人姓名"
                placeholder="预约人姓名" 
                :rules="[{ required: true, message: '请填写预约人姓名' }]"
            >
                <template 
                    v-if="!isReadonly" 
                    #button
                >
                    <van-uploader 
                        v-model="dataArr.sh_ex37" 
                        :readonly="isReadonly"
                        :preview-image="false" 
                        :before-delete="beforeDelete('sh_ex37')" 
                        :before-read="beforeRead" 
                        :after-read="afterRead('sh_ex37', true)"
                    >
                        <van-button 
                            size="small" 
                            icon="plus" 
                            type="primary" 
                            native-type="button"
                        >
                            拍照识别
                        </van-button>
                    </van-uploader>
                </template>
            </van-field>
            <van-field 
                v-model="formData.sh_ex6" 
                :readonly="isReadonly"
                required
                center
                type="number" 
                maxlength="11"
                name="sh_ex6" 
                label="联系电话"
                placeholder="联系电话" 
                :rules="[{ required: true, message: '请填写联系电话' },{ validator: isPhone, message: '请填写正确的联系电话' }]"
            />

            <van-field 
                v-model="formData.sh_ex35" 
                :readonly="isReadonly"
                required
                center
                name="sh_ex35" 
                label="预约人身份证"
                placeholder="预约人身份证" 
                :rules="[{ required: true, message: '请填写预约人身份证' },{ validator: validator3, message: '请填写正确的预约人身份证' }]"
            />
            <van-field 
                required
                readonly
                center
                name="sh_ex37" 
                label="预约人身份证"
                :rules="[{ validator: validator2('sh_ex37'), message: '请上传预约人身份证' }]"
            />
            <div class="uploader-box">
                <van-uploader 
                    v-model="dataArr.sh_ex37" 
                    :readonly="isReadonly"
                    :max-count="1" 
                    upload-text="预约人身份证" 
                    :before-delete="beforeDelete('sh_ex37')" 
                    :before-read="beforeRead" 
                    :after-read="afterRead('sh_ex37')"
                    :deletable="!isReadonly"
                >
                    <template #default>
                        <img src="@/assets/uploader/uploader.png" />
                    </template>
                </van-uploader>
            </div>
            <FixedButton v-if="!isReadonly" native-type="submit">提交</FixedButton>
        </van-form>
    </div>
</template>

<script lang="ts" setup>
    import { ref, reactive, markRaw, onBeforeMount } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import { showDialog, showLoadingToast, closeToast, showFailToast  } from 'vant'
    import MyHeader from '@/components/MyHeader.vue'
    import FixedButton from '@/components/FixedButton.vue'
    import FieldPopupPicker from '@/components/FieldPopupPicker.vue'
    import FieldPopupDatePicker from '@/components/FieldPopupDatePicker.vue'
    import FieldPopupEsign from '@/components/FieldPopupEsign.vue'
    import { GmazyuyApi, fileUploadBase64Ex, idOrc, getRecordDetailsApi } from '@/apis'
    import { isPhone, compressImg, isCardID, getSex, getAge } from '@/utils/utils.js'
    import { useStore } from '@/store'

    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    const isReadonly: boolean = route.query?.sh_id ? true : false
    const formData = ref({
        gaz_ex3: '',
        sh_ex6: '',
        sh_ex2: '',
        sh_ex3: '',
        sh_ex4: '',
        gaz_ex2: '',
        sh_ex35: '',
        sh_ex36: '',
        sh_ex37: '',
        sh_ex47: store.openid,
        gaz_ex1: '',
        sh_ex25: '',
        gaz_ex4: '',
        gaz_dat1: '',
        lt_ex25: '',
    })
    const dataArr = reactive({
        sh_ex36: [], //逝者身份证
        sh_ex37: [], //预约人身份证
    })
    
    onBeforeMount(async () => {
        if (isReadonly) {
            console.log('...........')
            // 获取数据
            getRecordDetailsApi({
                sh_id: route.query.sh_id
            }).then(res => {
                formData.value = res.data[0]
                if (formData.value.sh_ex36) {
                    dataArr.sh_ex36 = [{
                        url: formData.value.sh_ex36,
                        isImage: true
                    }]
                }
                if (formData.value.sh_ex37) {
                    dataArr.sh_ex37 = [{
                        url: formData.value.sh_ex37,
                        isImage: true
                    }]
                }
               
            })
        } else {
           
        }
    })
  
    

    // 校验函数返回 true 表示校验通过，false 表示不通过
    const validator = (val) => {
        if (isCardID(val)) {
            return false
        } else {
            // 逝者性别
            formData.value.sh_ex3 = getSex(val)
            // 逝者年龄
            formData.value.sh_ex4 = getAge(val)
            return true
        }
    }
    // 照片数组验证
    const validator2 = (field) => {
        return val => {
            console.log(val)
            console.log(field)
            if (dataArr[field].length == 0 || !formData.value[field]) {
                return false
            } else {
                return true
            }
        }
    }
    // 校验函数返回 true 表示校验通过，false 表示不通过
    const validator3 = (val) => {
        if (isCardID(val)) {
            return false
        } else {
            return true
        }
    }
    const beforeDelete = (data) => {
        return (file, detail) => {
            let arr = formData.value[data].split(',')
            arr.splice(detail.index, 1)
            formData.value[data] = arr.join(',')
            return true
        }
    }
    const beforeRead = (file) => {
        console.log(file)
        if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
            showFailToast('请上传 jpg/png 格式图片');
            return false;
        }
        return true;
    }
    const afterRead = (imgField, isIdOrc = false) => {
        return file => {
            file.status = 'uploading';
            file.message = '上传中...';
            // 执行压缩图片并上传
            let obj = new compressImg(file, afterRead2, imgField, isIdOrc, file )
            // console.log(obj)
            // console.log(obj.getMyf())
            // console.log(obj.getMyfb())
            // console.log(obj.myf)
            // console.log(obj.myfb)
        }
    }
    // 组件方法 获取 流
    const afterRead2 = (imgField, isIdOrc, file, obj) => {
        // failed done 
        // file.status = 'uploading';
        // file.message = '上传中...';
        // file.file: 文件 file.content: base64图片
        console.log(file)
        // let f = new FormData()
        // f.append('file', file.file)
        fileUploadBase64Ex({
            data: obj,
            sCode: 'fhsbyg'
        }).then(res => {
            // file.status = 'done';
            // file.message = '上传完成';
            console.log(res)

            if (imgField == 'sh_ex36' || imgField == 'sh_ex37') {
                // 拍照识按钮要显示不能设置maxCount=1，不然上传一张图就没了按钮
                if (dataArr[imgField].length > 1) {
                    dataArr[imgField].shift()
                }
                formData.value[imgField] = res[0].url
                // 用过拍照识别后续上传身份证都要进行idOrc验证信息
                if (isIdOrc) {
                    idOrc({
                        img: obj
                    }).then(res => {
                        if (res.idcard_number_type == 1) {
                            let obj = res.words_result

                            if (imgField == 'sh_ex36') {
                                formData.value.gaz_ex3 = obj['姓名'].words
                                formData.value.sh_ex2 = obj['公民身份号码'].words
                                validator(obj['公民身份号码'].words)
                                // formData.value.sh_ex3 = obj['性别'].words
                            } else if (imgField == 'sh_ex37') {
                                formData.value.gaz_ex2 = obj['姓名'].words
                                formData.value.sh_ex35 = obj['公民身份号码'].words
                            }
                        } else {
                            throw new Error('身份证验证失败')
                        }
                        file.status = 'done';
                        file.message = '上传完成';
                        
                    }).catch(err => {
                        console.log(err)
                        showFailToast('识别失败')
                        file.status = 'done';
                        file.message = '上传完成';
                    })
                } else {
                    file.status = 'done';
                    file.message = '上传完成';
                }

            } else {
                // formData.value[imgField] = res[0].url
                if (formData.value[imgField]) {
                    formData.value[imgField] = formData.value[imgField].concat(',', res[0].url)
                } else {
                    formData.value[imgField] = formData.value[imgField].concat(res[0].url)
                }
                file.status = 'done';
                file.message = '上传完成';
            }
            
        }).catch(err => {
            file.status = 'failed';
            file.message = '上传失败';
            console.log(dataArr[imgField])
            dataArr[imgField].pop()
            showFailToast('上传失败')
            console.log(err)
        })
    }






    const onFailed = (value) => {
        showDialog({
            title: '提示',
            message: value.errors[0].message
        })
    }
    const onSubmit = async (value) => {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0
        });
        
        GmazyuyApi({
            data: JSON.stringify(formData.value),
        }).then(res => {
            closeToast();
            if (res.status == '+OK') {
                showDialog({
                    title: '提示',
                    message: '提交成功！',
                }).then(() => {
                    router.push('/')                         
                });
            } else {
                showDialog({
                    title: '提示',
                    message: '网络异常，请稍后重试！',
                })
            }
            
        }).catch(err => {
            closeToast();
            showDialog({
                title: '提示',
                message: '网络异常，请稍后重试！',
            })
        })
    }
</script>
<style lang="scss" scoped>
    .repair {
        height: 100vh;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }
    :deep(.van-form) {
        // height: 550px;
        // height: 510px;
        flex: 1;
        overflow: scroll;
    }
    .uploader-box {
        border-bottom: 1px solid #999999;
        margin: 6px 15px;
        box-sizing: border-box;
        padding: 0px 0;
        height: 180px;
        overflow: hidden;
        img {
            width: 345px;
            height: 180px;
        }
        // 上传图片后图片大小
        :deep(.van-uploader__preview-image) {
            width: 345px;
            height: 180px;
        }
    }
    .my-card {
        background: #fff;
        border-bottom: 1px solid #efefef;
    }
    .dnt-box {
        border-bottom: 1px solid #efefef;
    }
</style>